import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:my_app_01/api/common.dart';
import 'package:my_app_01/api/dashboard.dart';
import 'package:my_app_01/components/MCard.dart';
import 'package:my_app_01/components/MEmpty.dart';
import 'package:my_app_01/components/MShimmer.dart';
import 'package:my_app_01/config.dart';
import 'package:my_app_01/model/User.dart';
import 'package:my_app_01/pages/common/list.dart';
import 'package:my_app_01/pages/menu/MenuShimmer.dart';
import 'package:my_app_01/utils/auth.dart';
import 'package:my_app_01/utils/index.dart';
import 'package:nil/nil.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  late UserModel? userInfo;

  @override
  void initState() {
    super.initState();
    userInfo = LoginPrefs.getUserInfo();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
              alignment: Alignment.topCenter,
              fit: BoxFit.cover,
              image: NetworkImage("https://meal.kmszzxt.cn/mp/images/bg-01.png")),
        ),
        child: ListView(
          padding: const EdgeInsets.only(top: 40, left: 20, right: 20, bottom: 20),
          children: [
            Text(
              key: const ValueKey("WelcomeText"),
              "下午好，${userInfo?.name ?? ""}",
              style: const TextStyle(color: Colors.black87, fontSize: 20, fontWeight: FontWeight.w600),
            ),
            Padding(
              key: const ValueKey("AccountNameText"),
              padding: const EdgeInsets.only(top: 5),
              child: Text(
                userInfo?.orgdepartname ?? "",
                style: const TextStyle(color: Colors.black54, fontSize: 14),
              ),
            ),
            const TopSwiperCard(),
            const FastMenuCard(),
            const HomeNoticeCard(),
            MCard(
              title: const Text(
                "待办事项",
                style: MCard.defaultTitleStyle,
              ),
              right: const Text(
                "查看详情",
                style: MCard.defaultRightTextStyle,
              ),
              icon: Icons.format_list_bulleted,
              rightTap: () {
                EasyLoading.showInfo("查看详情");
              },
              child: FutureBuilder(
                future: CommonApi.getTodoListByUser(count: 5),
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.waiting) {
                    return const MShimmer(
                      width: double.infinity,
                      height: 180,
                      margin: EdgeInsets.only(top: 10),
                    );
                  }
                  if (snapshot.connectionState == ConnectionState.done) {
                    List todoList = snapshot.data?['data']?['rows'];
                    return Column(
                      children: todoList.asMap().entries.map((e) {
                        return Container(
                          padding: const EdgeInsets.only(bottom: 8),
                          margin: const EdgeInsets.only(bottom: 8),
                          decoration: const BoxDecoration(
                            border: Border(
                              bottom: BorderSide(
                                color: Colors.black12,
                                width: 1,
                              ),
                            ),
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                e.value['title'],
                                style: TextStyle(
                                  overflow: TextOverflow.ellipsis,
                                  color: MyConfig.primaryColor,
                                  fontSize: 16,
                                ),
                                maxLines: 1,
                              ),
                              Padding(
                                padding: const EdgeInsets.only(top: 6, bottom: 6),
                                child: Text(
                                  e.value['content'] ?? '暂无内容',
                                  style: const TextStyle(
                                    overflow: TextOverflow.ellipsis,
                                    color: Colors.black54,
                                    fontSize: 14,
                                  ),
                                  maxLines: 2,
                                ),
                              ),
                              Row(
                                children: [
                                  Expanded(
                                    flex: 1,
                                    child: Text(
                                      "创建人:${e.value['createusername'] ?? "暂无"}",
                                      style: const TextStyle(
                                        overflow: TextOverflow.ellipsis,
                                        color: Colors.black54,
                                        fontSize: 12,
                                      ),
                                    ),
                                  ),
                                  Expanded(
                                    flex: 1,
                                    child: Text(
                                      "时间:${e.value['createtime']}",
                                      style: const TextStyle(
                                        overflow: TextOverflow.ellipsis,
                                        color: Colors.grey,
                                        fontSize: 12,
                                      ),
                                    ),
                                  ),
                                ],
                              )
                            ],
                          ),
                        );
                      }).toList(),
                    );
                  }
                  return nil;
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

/// 轮播图
class TopSwiperCard extends StatelessWidget {
  const TopSwiperCard({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: DashboardApi.getImageList(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const MShimmer(
            width: double.infinity,
            height: 180,
            margin: EdgeInsets.only(top: 10),
          );
        }
        if (snapshot.connectionState == ConnectionState.done) {
          var imgList = snapshot.data?['data']?['rows'];
          return snapshot.hasData && imgList != null && imgList.length > 0
              ? Card(
                  margin: const EdgeInsets.only(top: 10),
                  elevation: 6,
                  color: Colors.white,
                  surfaceTintColor: Colors.white,
                  clipBehavior: Clip.hardEdge,
                  shadowColor: Colors.black38,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: SizedBox(
                    height: 180,
                    child: PageView.builder(
                      itemCount: imgList.length,
                      itemBuilder: (BuildContext context, int index) {
                        var imgItem = imgList[index % imgList.length];
                        return SwiperItem(imgItem: imgItem);
                      },
                    ),
                  ),
                )
              : const MEmpty(message: "暂无图片数据");
        }
        return nil;
      },
    );
  }
}

class SwiperItem extends StatelessWidget {
  const SwiperItem({
    super.key,
    required this.imgItem,
  });

  final imgItem;

  @override
  Widget build(BuildContext context) {
    return Stack(
      fit: StackFit.expand,
      children: [
        Align(
          alignment: Alignment.topLeft,
          child: Image.network("${MyConfig.fileUrl}${imgItem['bimageurl']}",
              fit: BoxFit.cover, height: 180, width: double.infinity, errorBuilder: (context, error, stackTrace) {
            return Container(
              alignment: Alignment.center,
              color: Colors.black12,
              child: const Text("图片加载失败"),
            );
          }),
        ),
        Align(
          alignment: Alignment.bottomCenter,
          child: Container(
            width: double.infinity,
            padding: const EdgeInsets.all(8),
            color: Colors.black.withOpacity(.5),
            child: Text(
              '${imgItem['title']}',
              style: const TextStyle(
                color: Colors.white,
                fontSize: 14,
              ),
            ),
          ),
        ),
      ],
    );
  }
}

/// 通知卡片
class HomeNoticeCard extends StatelessWidget {
  const HomeNoticeCard({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: const EdgeInsets.only(top: 0),
      elevation: 6,
      color: Colors.white,
      surfaceTintColor: Colors.white,
      shadowColor: Colors.black38,
      clipBehavior: Clip.hardEdge,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
      ),
      child: Container(
        padding: const EdgeInsets.all(10),
        height: 80,
        child: Row(
          children: [
            Expanded(
              flex: 3,
              child: Image.asset(
                "images/notice.png",
                width: 40,
                height: 40,
              ),
            ),
            Expanded(
              flex: 10,
              child: Container(
                margin: const EdgeInsets.only(left: 15, right: 15),
                padding: const EdgeInsets.only(left: 15, right: 15),
                decoration: const BoxDecoration(
                  border: Border(
                    left: BorderSide(
                      color: Colors.black12,
                      width: 1,
                    ),
                    right: BorderSide(
                      color: Colors.black12,
                      width: 1,
                    ),
                  ),
                ),
                child: FutureBuilder(
                    future: DashboardApi.getNoticeList(),
                    builder: (context, snapshot) {
                      if (snapshot.connectionState == ConnectionState.waiting) {
                        return const Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            MShimmer(
                              width: double.infinity,
                              height: 20,
                              margin: EdgeInsets.only(top: 10),
                            ),
                            MShimmer(
                              width: 80,
                              height: 20,
                              margin: EdgeInsets.only(top: 10),
                            )
                          ],
                        );
                      }
                      if (snapshot.connectionState == ConnectionState.done) {
                        var noticeList = snapshot.data?['data']?['rows'];
                        return snapshot.hasData && noticeList != null && noticeList.length > 0
                            ? PageView.builder(
                                scrollDirection: Axis.vertical,
                                itemCount: noticeList.length,
                                itemBuilder: (BuildContext context, int index) {
                                  var noticeItem = noticeList[index % noticeList.length];
                                  return NoticeItem(noticeItem: noticeItem);
                                },
                              )
                            : const Text("暂无未读通知", style: TextStyle(color: Colors.black38, fontSize: 16));
                      }
                      return nil;
                    }),
              ),
            ),
            const Expanded(
              flex: 3,
              child: Row(
                children: [
                  Icon(
                    Icons.more_vert,
                    color: Colors.black38,
                    size: 16,
                  ),
                  Text(
                    "更多",
                    style: TextStyle(color: Colors.black38, fontSize: 16),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class NoticeItem extends StatelessWidget {
  const NoticeItem({
    super.key,
    required this.noticeItem,
  });

  final noticeItem;

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          noticeItem['name'],
          maxLines: 1,
          style: const TextStyle(fontSize: 16, height: 1.5),
        ),
        Text(
          noticeItem['publishtime'],
          maxLines: 1,
          style: const TextStyle(fontSize: 12, color: Colors.black54),
        ),
      ],
    );
  }
}

/// 快捷入口
class FastMenuCard extends StatelessWidget {
  const FastMenuCard({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: CommonApi.getMenuList(),
      builder: (context, snapshot) {
        Iterable menuList = [];
        if (snapshot.connectionState == ConnectionState.waiting) {
          EasyLoading.show(status: "加载中...");
          return Padding(
              padding: const EdgeInsets.only(top: 15, bottom: 10),
              child: GridView.builder(
                physics: const NeverScrollableScrollPhysics(),
                shrinkWrap: true,
                padding: const EdgeInsets.all(0.0),
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                    //横轴元素个数
                    crossAxisCount: 5,
                    //垂直单个子widget间距
                    mainAxisSpacing: 4,
                    //水平单个子widget间距
                    crossAxisSpacing: 4,
                    //item宽高比例
                    childAspectRatio: 1.0),
                itemBuilder: (context, index) {
                  return Container(
                    margin: const EdgeInsets.all(5),
                    child: const MShimmer(
                      width: 50,
                      height: 50,
                    ),
                  );
                },
                itemCount: 10,
              ));
        }
        if (snapshot.connectionState == ConnectionState.done) {
          EasyLoading.dismiss();
          if (snapshot.data?['data'] != null) {
            menuList = List.from(snapshot.data?['data']).where((e) => e['path'] != 'Layout');
          }
          if (menuList.isEmpty) {
            return const MEmpty(message: "暂无菜单数据");
          } else {
            return Padding(
              padding: const EdgeInsets.only(top: 15, bottom: 10),
              child: GridView.builder(
                physics: const NeverScrollableScrollPhysics(),
                shrinkWrap: true,
                padding: const EdgeInsets.all(0.0),
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  //横轴元素个数
                  crossAxisCount: 5,
                  //垂直单个子widget间距
                  mainAxisSpacing: 2,
                  //水平单个子widget间距
                  crossAxisSpacing: 2,
                  //item宽高比例
                  childAspectRatio: 1.0,
                ),
                itemBuilder: (context, index) {
                  var currentItem = menuList.elementAt(index);
                  return InkWell(
                    onTap: () async {
                      var result = await Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) {
                            return ListPage(
                              pageTitle: currentItem['name'],
                            );
                          },
                        ),
                      );
                    },
                    child: Column(
                      children: [
                        Icon(
                          IconData(MUtils.generateRandomEHex(5), fontFamily: 'MaterialIcons'),
                          size: 28,
                          color: Color.fromRGBO(Random().nextInt(256), Random().nextInt(256), Random().nextInt(256), 1),
                        ),
                        const SizedBox(
                          height: 5,
                        ),
                        Text(
                          "${currentItem['name']}",
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: const TextStyle(
                            fontSize: 14,
                          ),
                        )
                      ],
                    ),
                  );
                },
                itemCount: 10,
              ),
            );
          }
        }
        return nil;
      },
    );
  }
}
